package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.Group;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.widget.ExpandGridView;

import static android.content.ContentValues.TAG;

/**
 * Created by whc07 on 2017/12/7.
 */

public class GroupSettingActivity extends BaseActivity implements OnClickListener {
    private ImageView img_back;
    private TextView tv_groupname;
    private TextView txt_title;// 标题，成员总数
    int m_total = 0;// 成员总数
    private ExpandGridView gridview;// 成员列表
    // 修改群名称、置顶、、、、
    private RelativeLayout re_change_groupname;
    private RelativeLayout rl_switch_chattotop;
    private RelativeLayout rl_switch_block_groupmsg;
    private RelativeLayout re_clear;
    private CheckBox check_top, check_closetip;
    private Button exitBtn,msgBtn;
    private String hxid;
    private String group_name,group_id;// 群名称
    boolean is_admin = false;// 是否是管理员
    List<User> members = new ArrayList<User>();
    String longClickUsername = null;
    private 	GridAdapter adapter;

    private QuitGroupReceiver quitGroupReceiver;
    private DeleteMembersFromGroupReceiver deleteMembersFromGroupReceiver;

    private IntentFilter intentFilter;
    private IntentFilter intentFilter1;

    private AndroidClientService.SendBinder sendBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    ChatUser currentUser  = UserManager.getInstance(GroupSettingActivity.this).getCurrentUser();

    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_groupsetting);
        super.onCreate(savedInstanceState);
        initGroupBC();

        initControl();

        initData();
        setListener();
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);

    }


    private void  initData(){
        Intent intent = getIntent();
        group_name=intent.getStringExtra("groupname");
        tv_groupname.setText(group_name);

        Group group;
        group= WeTalkDB.create(GroupSettingActivity.this).queryGroupByName(group_name);
        String groupinfo = group.getUser_id();
        group_id=group.getGroup_id();
        if (groupinfo != null) {
            String[] manbers = groupinfo.split("、");
            if (manbers != null && manbers.length > 0) {
                m_total = manbers.length;
                txt_title.setText("聊天信息(" + String.valueOf(m_total) + ")");
                // 解析群组成员信息
                for (int i = 0; i < m_total; i++) {
                    User userinfo =  WeTalkDB.create(GroupSettingActivity.this).queryUserByid(manbers[i]);
                    User user = new User(userinfo.getUserName(),R.mipmap.a1);
                    members.add(user);
                }

                if (members.get(0).getUserName().equals(currentUser.getUserName())){
                    is_admin=true;
                }
            }
            RelativeLayout rvRight=(RelativeLayout)findViewById(R.id.rv_img_right);
            rvRight.setVisibility(View.GONE);
            RelativeLayout rvLeft = (RelativeLayout) findViewById(R.id.rv_img_back);
            rvLeft.setVisibility(View.VISIBLE);
            rvLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

        showMembers(members);
        }
    }

    protected void initControl() {
        txt_title = (TextView) findViewById(R.id.txt_title);
        txt_title.setText("群组信息");
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setVisibility(View.VISIBLE);
        tv_groupname = (TextView) findViewById(R.id.txt_groupname);
        gridview = (ExpandGridView) findViewById(R.id.gridview);

        re_change_groupname = (RelativeLayout) findViewById(R.id.re_change_groupname);
        rl_switch_chattotop = (RelativeLayout) findViewById(R.id.rl_switch_chattotop);
        rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
        re_clear = (RelativeLayout) findViewById(R.id.re_clear);
        check_top = (CheckBox)findViewById(R.id.check_top);
        check_closetip = (CheckBox)findViewById(R.id.check_closetip);

        exitBtn = (Button) findViewById(R.id.btn_exit_grp);
        msgBtn = (Button) findViewById(R.id.btn_msg_grp);

    }



    private void showMembers(List<User> members) {
        adapter = new GridAdapter(this, members);
        gridview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        gridview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (adapter.isInDeleteMode) {
                            adapter.isInDeleteMode = false;
                            adapter.notifyDataSetChanged();
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }


    protected void setListener() {
        re_change_groupname.setOnClickListener(this);
        rl_switch_chattotop.setOnClickListener(this);
        rl_switch_block_groupmsg.setOnClickListener(this);
        re_clear.setOnClickListener(this);
        exitBtn.setOnClickListener(this);
        msgBtn.setOnClickListener(this);
        img_back.setOnClickListener(this);
        tv_groupname.setOnClickListener(this);


        check_top.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    Toast.makeText(GroupSettingActivity.this,"置顶成功",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(GroupSettingActivity.this,"取消置顶",Toast.LENGTH_LONG).show();
                }
            }
        });
        check_closetip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    Toast.makeText(GroupSettingActivity.this,"屏蔽群消息",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(GroupSettingActivity.this,"取消屏蔽",Toast.LENGTH_LONG).show();
                }
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                Intent intent = new Intent(GroupSettingActivity.this,GroupListActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.btn_exit_grp:
                AlertDialog.Builder dialog=new AlertDialog.Builder(GroupSettingActivity.this);
                dialog.setTitle("删除群组并退出");
                dialog.setMessage("是否删除群组并退出？");
                dialog.setCancelable(false);
                dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        QuitGroup(currentUser.getUserID(),group_name,new PushListener(){
                            @Override
                            public void onSuccess() {
                                Toast.makeText(GroupSettingActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFailure(int var1, String var2) {
                                Toast.makeText(GroupSettingActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                        //finish();
                        Toast.makeText(GroupSettingActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    }
                });
                dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.show();
                break;
            case R.id.btn_msg_grp:
                //TODO 需要发送群组消息，要把群里的用户告诉聊天界面
                Intent msgGroup=new Intent(GroupSettingActivity.this,GroupChatActivity.class);
                msgGroup.putExtra("groupID",group_id);
                msgGroup.putExtra("groupName",group_name);
                startActivity(msgGroup);
                break;
            case R.id.txt_groupname:
                Intent intent1 = new Intent(GroupSettingActivity.this,ChangeGroupNameActivity.class);
                intent1.putExtra("extra_groupname",group_name);
                startActivity(intent1);
                finish();
                break;
            case R.id.re_clear:
                AlertDialog.Builder dialog1=new AlertDialog.Builder(GroupSettingActivity.this);
                dialog1.setTitle("清空聊天记录");
                dialog1.setMessage("是否清空聊天记录？");
                dialog1.setCancelable(false);
                dialog1.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        Toast.makeText(GroupSettingActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    }
                });
                dialog1.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog1.show();
                break;

            default:
                break;
        }
    }




    private class GridAdapter extends BaseAdapter {

        public boolean isInDeleteMode;
        private List<User> objects;
        Context context;

        public GridAdapter(Context context, List<User> objects) {

            this.objects = objects;
            this.context = context;
            isInDeleteMode = false;
        }


        @Override
        public View getView(final int position, View convertView,
                            final ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.item_chatsetting_gridview, null);
            }
            ImageView iv_avatar = (ImageView) convertView
                    .findViewById(R.id.iv_avatar);
            TextView tv_username = (TextView) convertView
                    .findViewById(R.id.tv_username);
            ImageView badge_delete = (ImageView) convertView
                    .findViewById(R.id.badge_delete);

            // 最后一个item，减人按钮
            if (position == getCount() - 1 && is_admin) {
                tv_username.setText("");
                badge_delete.setVisibility(View.GONE);
                iv_avatar.setImageResource(R.drawable.icon_btn_deleteperson);

                if (isInDeleteMode) {
                    // 正处于删除模式下，隐藏删除按钮
                    convertView.setVisibility(View.GONE);
                } else {

                    convertView.setVisibility(View.VISIBLE);
                }

                iv_avatar.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        isInDeleteMode = true;
                        notifyDataSetChanged();
                    }
                });

            } else if ((is_admin && position == getCount() - 2)
                    || (!is_admin && position == getCount() - 1)) { // 添加群组成员按钮
                tv_username.setText("");
                badge_delete.setVisibility(View.GONE);
                iv_avatar.setImageResource(R.drawable.jy_drltsz_btn_addperson);
                // 正处于删除模式下,隐藏添加按钮
                if (isInDeleteMode) {
                    convertView.setVisibility(View.GONE);
                } else {
                    convertView.setVisibility(View.VISIBLE);
                }
                iv_avatar.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //   进入选人页面
                        Intent intent = new Intent(GroupSettingActivity.this,AddGroupChatActivity.class);
                        intent.putExtra("GROUP_ID",group_name);
                        startActivity(intent);
                    }
                });
            } else { // 普通item，显示群组成员
                final User user1 = members.get(position);
                String usernick = user1.getUserName();
                final User user = WeTalkDB.create(GroupSettingActivity.this).queryFriendByName(usernick);
                final String useravatar = "http://pic.58pic.com/58pic/13/19/88/64J58PICydg_1024.jpg";
                tv_username.setText(usernick);
                iv_avatar.setImageResource(R.drawable.head);// TODO 网络加载头像
                iv_avatar.setTag(useravatar);
                if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete).setVisibility(
                            View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete).setVisibility(
                            View.INVISIBLE);
                }
                iv_avatar.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isInDeleteMode) {
                             //如果是删除自己，return
                            if (currentUser.getUserID().equals(user.getUserID())) {
                                Toast.makeText(GroupSettingActivity.this, "不能删除自己", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            AlertDialog.Builder dialog1=new AlertDialog.Builder(GroupSettingActivity.this);
                            dialog1.setTitle("删除群成员");
                            dialog1.setMessage("是否删除群成员？");
                            dialog1.setCancelable(false);
                            dialog1.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteMembersFromGroup(user.getUserID(),group_name,new PushListener(){
                                        @Override
                                        public void onSuccess() {
                                            Toast.makeText(GroupSettingActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onFailure(int var1, String var2) {
                                            Toast.makeText(GroupSettingActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    //finish();
                                    Toast.makeText(GroupSettingActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                            dialog1.setNegativeButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            dialog1.show();
//                            if (!NetUtils.hasNetwork(getApplicationContext())) {
//                                Toast.makeText(
//                                        getApplicationContext(),
//                                        getString(R.string.network_unavailable),
//                                        Toast.LENGTH_SHORT).show();
//                                return;
//                            }

                        } else {
                             //正常情况下点击user，可以进入用户详情
                            UserInfoActivity.actionStart(GroupSettingActivity.this,user,"look");
//                            Intent intent = new Intent(
//                                    GroupSettingActivity.this,
//                                    UserInfoActivity.class);
//                            intent.putExtra(Constants.NAME, user.getUserName());
//                            intent.putExtra(Constants.TYPE,
//                                    ChatActivity.CHATTYPE_SINGLE);
//                            intent.putExtra(Constants.User_ID,
//                                    user.getTelephone());
//                            startActivity(intent);
                            overridePendingTransition(R.anim.push_left_in,
                                    R.anim.push_left_out);
                        }
                    }
                });
            }
            return convertView;
        }

        @Override
        public int getCount() {
            if (is_admin) {
                return objects.size() + 2;
            } else {

                return objects.size() + 1;
            }
        }
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return objects.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
    }


    private void QuitGroup(String id,String name, final PushListener pushCallback)  {
        final String targetId = "sys_group";
        final String userId= UserManager.getInstance(GroupSettingActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
//        String user = WeTalkDB.create(GroupSettingActivity.this).queryGroupByName(name).getUser_id();
//        String[]array=user.split("、");
//        String[]member=new String[array.length-1];
//        int index=0;
//        for (int i = 0;i<array.length;i++){
//            if (array[i].equals(userId)) {
//            }else{
//                member[index]=array[i];
//                index++;
//            }
//        }
//
//            String userid = StringUtils.join(member, "、");
        String gidArray = WeTalkDB.create(GroupSettingActivity.this).queryGroupByName(name).getGroup_id();
        String [] nameArray = gidArray.split("_");
        String gid = nameArray[0];
        try {
            json.put("gid",gid);
            json.put("mid",id);
            //json.put("gname",name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"quitGroup",bs);
                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }

    private void deleteMembersFromGroup(String id,String name, final PushListener pushCallback ){//TODO
        final String targetId = "sys_group";
        final String userId= UserManager.getInstance(GroupSettingActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
        Group group = WeTalkDB.create(GroupSettingActivity.this).queryGroupByName(name);
//        String user = group.getUser_id();
//        String[]array=user.split("、");
//        String[]member=new String[array.length-1];
//        int index=0;
//        for (int i = 0;i<array.length;i++){
//            if (array[i].equals(id)) {
//            }else{
//                member[index]=array[i];
//                index++;
//            }
//        }

//        String userid = StringUtils.join(member, "、");

        String[]M=group.getGroup_id().split("_");
        try {
            json.put("mid",id);
            json.put("uid",currentUser.getUserID());
            json.put("gid",M[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"delMember",bs);
                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //initData();
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }
    //注册广播接收器
    private void initGroupBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_QUIT_GROUP);
        quitGroupReceiver=new QuitGroupReceiver();
        registerReceiver(quitGroupReceiver,intentFilter);
        intentFilter1=new IntentFilter(WeTalkConfig.BROADCAST_DELETE_MEMBER_GROUP);
        deleteMembersFromGroupReceiver=new DeleteMembersFromGroupReceiver();
        registerReceiver(deleteMembersFromGroupReceiver,intentFilter1);


    }
    //广播接收器
    private class QuitGroupReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content=intent.getStringExtra("result");
            try {
                JSONObject json=new JSONObject(content);
                String group_name = json.getString("gname");
                WeTalkDB.create(GroupSettingActivity.this).deleteGroup(group_name);
                Toast.makeText(context, "退出成功", Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 广播终结
            //abortBroadcast();
            finish();
        }
    }

    private class DeleteMembersFromGroupReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content=intent.getStringExtra("result");
            try {
                JSONObject json=new JSONObject(content);
                String groupid = json.getString("gid")+"_g";
                String mname = json.getString("mname");
                User user = WeTalkDB.create(GroupSettingActivity.this).queryUserByName(mname);
                String mid = user.getUserID();
                Group newgroup=WeTalkDB.create(GroupSettingActivity.this).queryGroupByID(groupid);
                String[] array = newgroup.getUser_id().split("、");
                String[] member=new String[array.length-1];
                int index=0;
                for (int i = 0;i<array.length;i++){
                    if (array[i].equals(mid)) {
                    }else{
                        member[index]=array[i];
                        index++;
                    }
                }
                    String userid = StringUtils.join(member, "、");

                newgroup.setUser_id(userid);
                WeTalkDB.create(GroupSettingActivity.this).modifyGroupInfo(newgroup);
                Toast.makeText(context, "删除成员成功", Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 广播终结
            abortBroadcast();
            members.clear();
            adapter.notifyDataSetChanged();
            initData();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(quitGroupReceiver);
        unregisterReceiver(deleteMembersFromGroupReceiver);
        unbindService(connection);
    }
}

